package com.datastructure.test.expandtree;

import java.util.ArrayList;

public class ExpandTree {

    public int number;
    public static void main(String[] args) {

    }

    public void expandTree (TreeNode root) {
        // write code here
        if(root==null){
            return;
        }
        computeTreeNumber(root);
        ArrayList<TreeNode> treeNodeArrayList = new ArrayList<>(number);
        doExpandTree(root,treeNodeArrayList);
        TreeNode temp = root;
        temp.left=null;
        for (int i = 1; i < treeNodeArrayList.size(); i++) {
            temp.right=treeNodeArrayList.get(i);
            temp.right.left=null;
            temp=temp.right;
        }
    }

    public void computeTreeNumber(TreeNode root){
        if(root!=null){
            number++;
        } else {
            return;
        }
        computeTreeNumber(root.left);
        computeTreeNumber(root.right);
    }

    private void doExpandTree(TreeNode root,ArrayList<TreeNode> treeNodeArrayList) {
        if(root!=null){
            treeNodeArrayList.add(root);
        }else {
            return;
        }
        if(root.left!=null){
            doExpandTree(root.left,treeNodeArrayList);
        }
        if(root.right!=null){
            doExpandTree(root.right,treeNodeArrayList);
        }
    }

    TreeNode last = null;
    public void expandTree1 (TreeNode root) {
        // write code here

        if (root == null) {
            return;
        }

        expandTree1(root.right);
        expandTree1(root.left);
        root.right = last;
        root.left = null;
        last = root;

    }
}

class TreeNode {
   int val = 0;
   TreeNode left = null;
   TreeNode right = null;
   public TreeNode(int val) {
     this.val = val;
   }
 }
